import { join } from 'node:path'
import url from 'node:url'
import { BrowserWindow, shell } from 'electron'
import { is } from '@electron-toolkit/utils'
import icon from '../../../resources/icon.png?asset'
import { WINDOWS } from '../constants'

export function createWindow (options: CreateWindowOptions): BrowserWindow {
  const win = new BrowserWindow({
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      webSecurity: process.env.NODE_ENV === 'production', // 解决开发环境无法使用 file: 协议加载图标的问题
    },
    ...options,
  })

  if (options.openDevTools) {
    win.webContents.openDevTools()
  }

  win.on('ready-to-show', () => {
    if (options.defaultVisible) {
      win.show()
    }
  })

  win.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  const hash = options.hash || ''

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    win.loadURL(`${process.env['ELECTRON_RENDERER_URL']}${hash}`)
  } else {
    win.loadURL(
      url.format({
        pathname: join(__dirname, '../renderer/index.html'),
        protocol: 'file',
        slashes: true,
        hash: options.hash?.slice(2),
      }),
    )
  }

  return win
}

export function getWindow (type: WindowType): BrowserWindow {
  let win = BrowserWindow.fromId(WINDOWS[type].id)
  if (!win) {
    win = createWindow(WINDOWS[type].options)
    WINDOWS[type].id = win.id

    if (type === 'search') {
      win.addListener('blur', () => {
        // 开发环境失焦不关闭窗口，方便调试
        if (process.env.NODE_ENV !== 'development' && win) {
          win.hide()
        }
      })

      win.addListener('show', () => {
        // 显示窗口的时候聚焦输入框
        if (win) {
          win.webContents.send('show-search-window')
        }
      })
    }
  }

  return win
}
